const express = require('express');
const AipSpeechClient = require('baidu-aip-sdk').speech;
const fs = require('fs');
const https = require('https');
const app = express();
const multer  = require('multer');
const APP_ID = "15174686";
const CLIENT_ID = 'jh9Iy7bzaseaW6T3255zCAdh';
const CLIENT_SECRET = 'M5y7Tg9gPPprdeqoWfN5pWUuhNsXeiiY';
const BAIDU_CHAT_HOST = 'aip.baidubce.com'; 
const BAIDU_CHAT_PATH = '/rpc/2.0/unit/bot/chat';
const SERVICE_ID = 'S11034';

const upload = multer({ dest: 'upload/' });

const sendChatMsg = (token,query) => {
    const requestData = {
        version : '2.0',
        log_id :  `${new Date().getTime}_chair`,
        service_id : SERVICE_ID,
        request : {
            query,
            'user_id' : 'ME',
            'bernard_level' : 1,
            'client_session' : '{"client_results":"", "candidate_options":[]}',
            'updates': '',
            'query_info' : {
                'asr_candidates': [],
                'type': 'TEXT',
                'source': 'KEYBOARD'
            }
        },
        bot_id : '23748',
        bot_session : "",
        sessionId : null,
        sysRememberSkills : []
    };
    return new Promise((resolve, reject) => {
        const request = https.request({
            hostname: BAIDU_CHAT_HOST,
            path: `${BAIDU_CHAT_PATH}?access_token=${token}`,
            method: 'POST',
            headers: {
                'Content-Type': 'application/json; charset=UTF-8'
            },
        },(response) => {
            let data = ''
            response.on('data', s => data+=s);
            response.on('end', () => resolve(JSON.parse(data)));
        });
        
        request.write(JSON.stringify(requestData));
        request.end();
    });
}

/**
 * 获取accesstoken
 */
const getAccessToken = () => {
    return new Promise((resolve, reject) => {
       const authConfig = require('./config/auth.json');
       resolve(authConfig.access_token);
    });
}
 

app.set('view engine','ejs') ;
app.set('views', __dirname + '/views') ;

app.get('/', (req,res) => {
    res.render('index',{name:'ejs case'}) ;
});

app.post('/upload', upload.single('file'), function(req, res, next){
    const file = req.file;
    // console.log('文件类型：%s', file.mimetype);
    // console.log('原始文件名：%s', file.originalname);
    // console.log('文件大小：%s', file.size);
    // console.log('文件保存路径：%s', file.path);
    const voice = fs.readFileSync(file.path);
    const voiceBuffer = new Buffer(voice);
    //console.log(voiceBuffer.length);

    // 新建一个对象，建议只保存一个对象调用服务接口
    const client = new AipSpeechClient(APP_ID, CLIENT_ID, CLIENT_SECRET);

    // 识别本地文件
    client.recognize(voiceBuffer, 'pcm', 16000).then(function (result) {
        console.log('<recognize>: ' + JSON.stringify(result));
        getAccessToken()
            .then((token) => {
                return sendChatMsg(token,result['result'][0]);
            })
            .then(data => {
                console.log(data);
                res.send({
                    result: '0', 
                    data : {
                        '音频内容' : result['result'][0],
                        '机器人回复' : JSON.stringify(data)
                    }
                });
            })
            .catch(e => {
                console.log(e);
            }); 


        
    }, function(err) {
        console.log(err);
    });
});

app.get('/chat', function(req, res){
    const {msg} = req.query;
    getAccessToken()
        .then((token) => {
            return sendChatMsg(token,msg);
        })
        .then(data => {
            console.log(data);
            res.send(JSON.stringify(data));
        })
        .catch(e => {
            console.log(e);
        }); 

});

app.listen(3000);